﻿using AchieveBLL;
using AchieveCommon;
using AchieveEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using AchieveManageWeb.Models.ActionFilters;
using AchieveManageWeb.Models;
using AchieveDAL;

namespace AchieveManageWeb.Controllers
{
        [AchieveManageWeb.App_Start.JudgmentLogin]
    public class RDController : Controller
    {
        //
        // GET: /RD/

        public ActionResult Index()
        {
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "研发管理")); //日志记录
            return View();
        }
        public ActionResult RDEdit()
        {
            return View();
        }

        /// <summary>
        /// 研发项目清单的查询处理
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRDList()
        {
            string strWhere = "1=1";
            string sort = Request["sort"] == null ? "ProjectID" : Request["sort"];
            string order = Request["order"] == null ? "desc" : Request["order"];
            string view = Request["view"] == null ? "PMMaintain" : Request["view"];

            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);//每页输出数量

            string ProjectID = Request["ProjectID"] == null ? "" : Request["ProjectID"];
            string ProjectNo = Request["ProjectNo"] == null ? "" : Request["ProjectNo"];
            string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];

            string CreateTimeS = Request["CreateTime"] == null ? "" : Request["CreateTime"];
            string CreateTimeE = Request["CreateTime"] == null ? "" : Request["CreateTime"];
            string status = (Request["status"] == null || Request["status"] == "select") ? "" : Request["status"];//0,1,2 未确认、已确认，已完成

            if (ProjectID.Trim() != "" && !SqlInjection.GetString(ProjectID))   //防止sql注入
                strWhere += string.Format(" and ProjectID = '{0}'", ProjectID.Trim());
            if (ProjectNo.Trim() != "" && !SqlInjection.GetString(ProjectNo))
                strWhere += string.Format(" and ProjectNo like '%{0}%'", ProjectNo.Trim());
            if (ProjectName.Trim() != "" && !SqlInjection.GetString(ProjectName))
                strWhere += string.Format(" and ProjectName like '%{0}%'", ProjectName.Trim());
            if (status.Trim() != "" && !SqlInjection.GetString(status))
                strWhere += string.Format(" and status = {0}", Convert.ToInt32(status.Trim()));

            if (CreateTimeS.Trim() != "")
                strWhere += " and CreateTime > '" + CreateTimeS.Trim() + "'";
            if (CreateTimeE.Trim() != "")
                strWhere += " and CreateTime < '" + CreateTimeE.Trim() + "'";

            string content = "";
            if (view == "RDGrid")//datagrid
            {
                int totalCount;   //输出参数 
              
                DataTable dt = RDBLL.GetRDList( sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
            
                string strJson = AchieveCommon.JsonHelper.ToJson(dt);
                content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
            }
            if (view == "RDGantt")
            {
                //     int totalCount;   //输出参数
                // pagesize = 5;//限制甘特图输出数据量
                //DataTable dt = new ProjectBLL().GetDataTablePager("ICMO", "FBillNo,FStatus,FPlanCommitDate,FPlanFinishDate,FStartDate,FFinishDate,FItemID", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
                //string strJson = ToGanttJson(dt);
                //content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
            }

            return Content(content);
        }
        /// <summary>
        /// 获取项目的节点详情
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRDNodes()
        {
            //首先获取前台传递过来的参数
            string strWhere = "1=1";
            string view = Request["view"] == null ? "PMMaintain" : Request["view"];
            string ProjectID = Request["ProjectID"] == null ? "" : Request["ProjectID"];
            string ProjectNo = Request["ProjectNo"] == null ? "" : Request["ProjectNo"];
            string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];
            if (ProjectID.Trim() != "" && !SqlInjection.GetString(ProjectID))   //防止sql注入
                strWhere += string.Format(" and ProjectID = '{0}'", ProjectID.Trim());
            string content = "";
            try
            {
                string sqlstr = string.Format("select * from tbRDNode where ProjectID='{0}'", ProjectID);
                DataTable dt = AchieveCommon.SqlHelper.GetDataTable(SqlHelper.connStr, sqlstr);
                string strJson = AchieveCommon.JsonHelper.ToJson(dt);
                content = "{\"success\": true ,\"rows\":" + strJson + "}";
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"获取数据失败," + ex.Message.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
            }

            return Content(content);
        }
        /// <summary>
        /// 获取附件列表清单，AppendListID
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAppendList()
        {
            //首先获取前台传递过来的参数
            string strWhere = "1=1";
            //string view = Request["view"] == null ? "PMMaintain" : Request["view"];
            string AppendListID = Request["AppendListID"] == null ? "" : Request["AppendListID"];
            //string ProjectNo = Request["ProjectNo"] == null ? "" : Request["ProjectNo"];
            //string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];
            if (AppendListID.Trim() != "" && !SqlInjection.GetString(AppendListID))   //防止sql注入
                strWhere += string.Format(" and AppendListID = '{0}'", AppendListID.Trim());
            string content = string.Empty;
            try
            {
                string sqlstr = string.Format("select AppendID,AppendName,AppendPath,UpdateTime,UpdateBy from tbAppendInfo where AppendListID='{0}'", AppendListID);
                DataTable dt = AchieveCommon.SqlHelper.GetDataTable(SqlHelper.connStr, sqlstr);
                string strJson = AchieveCommon.JsonHelper.ToJson(dt);
                content = "{\"success\": true ,\"rows\":" + strJson + "}";
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"获取数据失败," + ex.Message.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
            }

            return Content(content);
        }


        public ActionResult AddNewProject()
        {
            UserEntity uInfo = ViewData["Account"] as UserEntity;
            try
            {
                string ProjectID = SqlHelper.GetSerialNumber("tbRDMain", "ProjectID");
                string ProjectNo = string.IsNullOrWhiteSpace(Request["ProjectNo"]) ? "RD" + ProjectID : Request["ProjectNo"];
                string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];
                string ProjectManager = Request["ProjectManager"] == null ? "" : Request["ProjectManager"];
                string ProjectClerk = Request["ProjectClerk"] == null ? "" : Request["ProjectClerk"];
                string Remark = Request["Remark"] == null ? "" : Request["Remark"];
                string Department = Request["Department"] == null ? "" : Request["Department"];
                string RDType = Request["RDType"] == null ? "" : Request["RDType"];
                decimal RDEstCost = string.IsNullOrWhiteSpace(Request["RDEstCost"]) ? 0 : Convert.ToDecimal(Request["RDEstCost"]);
                decimal estPrice = string.IsNullOrWhiteSpace(Request["estPrice"]) ? 0 : Convert.ToDecimal(Request["estPrice"]);
                int pLevel = string.IsNullOrWhiteSpace(Request["pLevel"]) ? 0 : Convert.ToInt32(Request["pLevel"]);
                decimal aFactor = string.IsNullOrWhiteSpace(Request["aFactor"]) ? 0 : Convert.ToDecimal(Request["aFactor"]);
                decimal iFactor = string.IsNullOrWhiteSpace(Request["iFactor"]) ? 0 : Convert.ToDecimal(Request["iFactor"]);
                string startTime = string.IsNullOrWhiteSpace(Request["startTime"]) ? null : Request["startTime"];
                string endTime = string.IsNullOrWhiteSpace(Request["endTime"]) ? null : Request["endTime"];
                string FName = Request["FName"] == null ? "" : Request["FName"];


                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（Remark）中存在非法字符！\",\"success\":false}");
                }
                if (Request["Department"] == null)
                {
                    return Content("{\"msg\":\"请选择部门！\",\"success\":false}");

                }


                RDMainEntity r = new RDMainEntity();

                r.aFactor = aFactor;
                r.Department = Department;
                //r.endTime = null;
                //r.endTime = Convert.ToDateTime(endTime);
                if (endTime != null)
                {
                    r.endTime = Convert.ToDateTime(endTime);
                }
                // r.endTime =  string.IsNullOrWhiteSpace(endTime) ? DateTime.MaxValue : Convert.ToDateTime(endTime);
                r.estPrice = estPrice;
                r.FName = FName;
                r.iFactor = iFactor;
                r.pLevel = pLevel;
                r.ProjectClerk = ProjectClerk;
                r.ProjectID = ProjectID;
                r.ProjectManager = ProjectManager;
                r.ProjectName = ProjectName;
                r.ProjectNo = ProjectNo;
                r.RDEstCost = RDEstCost;
                r.RDType = RDType;
                if (startTime != null)
                {
                    r.startTime = Convert.ToDateTime(startTime);
                }
                //  r.startTime = string.IsNullOrWhiteSpace(startTime)? DateTime.MaxValue: Convert.ToDateTime(startTime);
                r.UpdateBy = uInfo.AccountName;
                r.UpdateTime = DateTime.Now;
                r.Add();

                
               

                List<string> sqllist = new List<string>();
                //生成增加主表记录sql
                //string mainsql = string.Format("insert into tbRDMain (ProjectID,ProjectNo,ProjectName,ProjectManager,ProjectClerk,Remark,CreateBy,CreateTime,department) ");
                //mainsql += string.Format(" values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}');", ProjectID, ProjectNo, ProjectName, ProjectManager, ProjectClerk, Remark, uInfo.AccountName, DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"), Department);
                //sqllist.Add(mainsql);


                //生成添加节点子表SQL                
                string InfoID = AchieveCommon.SqlHelper.GetSerialNumber("tbRDNode", "InfoID");//获取起始节点编号
                string AppendListID = AchieveCommon.SqlHelper.GetSerialNumber("tbRDNode", "AppendListID");//获取起始附件清单编号
                long lastInfoID = long.Parse(InfoID);
                long lastAppendListID = long.Parse(AppendListID);
                //预研立项
                StringBuilder strSqlbs = new StringBuilder();
                strSqlbs.Append("insert into tbRDNode(InfoID,projectID,nodeid,nodename,AppendListID) ");
                strSqlbs.AppendFormat(" values ('{0}','{1}',{2},'{3}','{4}');", lastInfoID++.ToString(), ProjectID, 11, "预研立项", lastAppendListID++.ToString());
                sqllist.Add(strSqlbs.ToString());
                //初步设计
                StringBuilder strSqlty = new StringBuilder();
                strSqlty.Append("insert into tbRDNode(InfoID,projectID,nodeid,nodename,AppendListID) ");
                strSqlty.AppendFormat(" values ('{0}','{1}',{2},'{3}','{4}');", lastInfoID++.ToString(), ProjectID, 12, "初步设计", lastAppendListID++.ToString());
                sqllist.Add(strSqlty.ToString());
                //工程设计
                StringBuilder strSqldn = new StringBuilder();
                strSqldn.Append("insert into tbRDNode(InfoID,projectID,nodeid,nodename,AppendListID) ");
                strSqldn.AppendFormat(" values ('{0}','{1}',{2},'{3}','{4}');", lastInfoID++.ToString(), ProjectID, 13, "工程设计", lastAppendListID++.ToString());
                sqllist.Add(strSqldn.ToString());
                //样机制作
                StringBuilder strSqlme = new StringBuilder();
                strSqlme.Append("insert into tbRDNode(InfoID,projectID,nodeid,nodename,AppendListID) ");
                strSqlme.AppendFormat(" values ('{0}','{1}',{2},'{3}','{4}');", lastInfoID++.ToString(), ProjectID, 14, "样机制作", lastAppendListID++.ToString());
                sqllist.Add(strSqlme.ToString());
                //首销成功
                StringBuilder strSqlcn = new StringBuilder();
                strSqlcn.Append("insert into tbRDNode(InfoID,projectID,nodeid,nodename,AppendListID) ");
                strSqlcn.AppendFormat(" values ('{0}','{1}',{2},'{3}','{4}');", lastInfoID++.ToString(), ProjectID, 15, "首销成功", lastAppendListID++.ToString());
                sqllist.Add(strSqlcn.ToString());
                int id = 0;
                id = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, sqllist);
                if (id > 0)
                {
                    AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "研发管理", "添加项目"+ProjectID,ProjectName)); //日志记录
                    return Content("{\"msg\":\"添加成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"添加失败！\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"添加失败," + ex.Message.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
            }

        }

        /// <summary>
        /// 根据projectid删除项目主表即节点子表，不处理附件！
        /// </summary>
        /// <returns></returns>
        public ActionResult DelProjectByID()
        {
            try
            {
                string projectID = Request["ID"] == null ? "" : Request["ID"];
                if (!string.IsNullOrEmpty(projectID))
                {
                    List<string> sqllist = new List<string>();
                    sqllist.Add(string.Format("delete tbRDMain where ProjectID = '{0}';", projectID));
                    sqllist.Add(string.Format("delete tbRDNode where ProjectID = '{0}';", projectID));
                    int x = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, sqllist);
                    if (x > 0)
                    {
                        AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "研发管理", "删除项目"+projectID)); //日志记录
                        return Content("{\"msg\":\"删除成功！\",\"success\":true}");
                    }
                    else
                    {
                        return Content("{\"msg\":\"删除失败！\",\"success\":false}");
                    }
                }
                else
                {
                    return Content("{\"msg\":\"删除失败！项目id为空\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"删除失败," + ex.Message + "\",\"success\":false}");
            }
        }

        /// <summary>
        /// 编辑项目单据主信息、基本信息
        /// </summary>
        /// <returns></returns>
        public ActionResult updateRDMain()
        {
             UserEntity uInfo = ViewData["Account"] as UserEntity;
            try
            {
                string ProjectID;
                if (string.IsNullOrWhiteSpace(Request["ProjectID"]))
                {
                    throw new Exception("没有获取到ProjectID");
                }
                else
                {
                    ProjectID = Request["ProjectID"];
                }
                string ProjectNo = string.IsNullOrWhiteSpace(Request["ProjectNo"]) ? "RD" + ProjectID : Request["ProjectNo"];
                string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];
                string ProjectManager = Request["ProjectManager"] == null ? "" : Request["ProjectManager"];
                string ProjectClerk = Request["ProjectClerk"] == null ? "" : Request["ProjectClerk"];
                string Remark = Request["Remark"] == null ? "" : Request["Remark"];
                string Department = Request["Department"] == null ? "" : Request["Department"];
                string RDType = Request["RDType"] == null ? "" : Request["RDType"];   
                decimal RDEstCost = string.IsNullOrWhiteSpace(Request["RDEstCost"])? 0 :Convert.ToDecimal(Request["RDEstCost"]);
                decimal estPrice = string.IsNullOrWhiteSpace(Request["estPrice"]) ? 0 : Convert.ToDecimal(Request["estPrice"]);
                int pLevel = string.IsNullOrWhiteSpace(Request["pLevel"]) ? 0 : Convert.ToInt32(Request["pLevel"]);
                decimal aFactor = string.IsNullOrWhiteSpace(Request["aFactor"]) ? 0 : Convert.ToDecimal(Request["aFactor"]);
                decimal iFactor = string.IsNullOrWhiteSpace(Request["iFactor"]) ? 0 : Convert.ToDecimal(Request["iFactor"]);
                string startTime = string.IsNullOrWhiteSpace(Request["startTime"]) ? null : Request["startTime"];
                string endTime = string.IsNullOrWhiteSpace(Request["endTime"]) ? null : Request["endTime"];
                string FName = Request["FName"] == null ? "" : Request["FName"];
                
                RDMainEntity r = new RDMainEntity();
                r.aFactor = aFactor;
                r.Department = Department;
                //r.endTime = null;
                //r.endTime = Convert.ToDateTime(endTime);
                if (endTime!=null)
                {
                    r.endTime = Convert.ToDateTime(endTime);
                }
               // r.endTime =  string.IsNullOrWhiteSpace(endTime) ? DateTime.MaxValue : Convert.ToDateTime(endTime);
                r.estPrice = estPrice;
                r.FName = FName;
                r.iFactor = iFactor;
                r.pLevel = pLevel;
                r.ProjectClerk = ProjectClerk;
                r.ProjectID = ProjectID;
                r.ProjectManager = ProjectManager;
                r.ProjectName = ProjectName;
                r.ProjectNo = ProjectNo;
                r.RDEstCost = RDEstCost;
                r.RDType = RDType;
                if (startTime != null)
                {
                    r.startTime = Convert.ToDateTime(startTime);
                }
              //  r.startTime = string.IsNullOrWhiteSpace(startTime)? DateTime.MaxValue: Convert.ToDateTime(startTime);
                r.UpdateBy = uInfo.AccountName;
                r.UpdateTime = DateTime.Now;
         


            //    if (SqlInjection.GetString(Remark))
            //    {
            //        return Content("{\"msg\":\"更新失败！备注（remark）中存在非法字符！\",\"success\":false}");
            //    }

               
            //    StringBuilder strSql = new StringBuilder();
            //    strSql.Append("update tbRDMain set ");
            //    strSql.Append("ProjectNo =@ProjectNo,ProjectName=@ProjectName,ProjectManager=@ProjectManager,ProjectClerk=@ProjectClerk,Remark=@Remark,department=@department,UpdateTime=@UpdateTime,UpdateBy=@UpdateBy");
            //    strSql.Append(" where ProjectID=@ProjectID ");
            //    SqlParameter[] parameters = {
            //            new SqlParameter("@ProjectID", ProjectID) , 
            //            new SqlParameter("@ProjectNo", ProjectNo) ,            
            //            new SqlParameter("@ProjectName",ProjectName) ,            
            //            new SqlParameter("@ProjectManager",ProjectManager) ,            
            //            new SqlParameter("@ProjectClerk", ProjectClerk) ,            
            //            new SqlParameter("@Remark", Remark) ,      
            //             new SqlParameter("@department", Department) ,      
            //            new SqlParameter("@UpdateTime", DateTime.Now) ,            
            //            new SqlParameter("@UpdateBy", uInfo.AccountName) ,            
                      
            //};
            //    int id = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, strSql.ToString(), parameters);
                if (r.Update())
                {
                    return Content("{\"msg\":\"更新成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"更新失败！\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"更新失败," + ex.Message.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
            }

        }

        /// <summary>
        /// 项目管理--更新项目节点信息，数据更新操作
        /// </summary>
        /// <returns></returns>
        public ActionResult updateRDNode()
        {
            try
            {
                UserEntity uInfo = ViewData["Account"] as UserEntity;
                string updateby = uInfo.RealName;
                string ProjectID = Request["ProjectID"];
                
                string PSTime = Request["bsPSTime"];
                string PETime = Request["bsPETime"];
                string RSTime = Request["bsRSTime"];
                string RETime = Request["bsRETime"];
                string Remark = Request["bsRemark"];
                string executor = Request["bsExecutor"];                
                int status = Convert.ToBoolean( Request["bsComplete"])?1:0;
                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（预研立项Remark）中存在非法字符！\",\"success\":false}");
                }
               
               RDBLL.updateNode("11", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName,status, Remark);//预研立项
                
                PSTime = Request["tyPSTime"];
                PETime = Request["tyPETime"];
                RSTime = Request["tyRSTime"];
                RETime = Request["tyRETime"];
                Remark = Request["tyRemark"];
                executor = Request["tyExecutor"];
                status = Convert.ToBoolean(Request["tyComplete"]) ? 1 : 0;
                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（初步设计Remark）中存在非法字符！\",\"success\":false}");
                }

                RDBLL.updateNode("12", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName,status, Remark);//初步设计
                PSTime = Request["dnPSTime"];
                PETime = Request["dnPETime"];
                RSTime = Request["dnRSTime"];
                RETime = Request["dnRETime"];
                Remark = Request["dnRemark"];
                executor = Request["dnExecutor"];
                status = Convert.ToBoolean(Request["dnComplete"]) ? 1 : 0;
                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（工程设计Remark）中存在非法字符！\",\"success\":false}");
                }
               RDBLL.updateNode("13", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName,status, Remark);//工程设计

                PSTime = Request["mePSTime"];
                PETime = Request["mePETime"];
                RSTime = Request["meRSTime"];
                RETime = Request["meRETime"];
                Remark = Request["meRemark"];
                status = Convert.ToBoolean(Request["meComplete"]) ? 1 : 0;
                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（样机制作Remark）中存在非法字符！\",\"success\":false}");
                }
                executor = Request["meExecutor"];

                RDBLL.updateNode("14", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName,status, Remark); //样机制作

                PSTime = Request["cnPSTime"];
                PETime = Request["cnPETime"];
                RSTime = Request["cnRSTime"];
                RETime = Request["cnRETime"];
                Remark = Request["cnRemark"];
                status = Convert.ToBoolean(Request["cnComplete"]) ? 1 : 0;
                executor = Request["cnExecutor"];
                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（首销成功Remark）中存在非法字符！\",\"success\":false}");
                }
               RDBLL.updateNode("15", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName,status, Remark);//首销成功 
                return Content("{\"msg\":\"修改成功！\",\"success\":true}");

            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"修改失败," + ex.Message + "\",\"success\":false}");
            }
        }
       
       

    }
}
